/*
 * @Description:Druid
 * 
 * @Author: rendc
 * 
 * @Date: 2024-11-19 11:32:28
 * 
 * @LastEditors: rendc
 * 
 * @LastEditTime: 2024-11-19 15:52:32
 */
package com.briup;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DruidTest {
  @Test
  public void test() {
    // 声明连接对象
    Connection conn = null;
    // 声明操作对象
    // 1. Statement - 容易被sql注入
    // 2. PreparedStatement
    PreparedStatement pstmt = null;
    // 声明结果集对象
    ResultSet rs = null;
    // 1. 加载配置文件
    Properties properties = new Properties();
    InputStream iStream = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
    try {
      properties.load(iStream);
      // properties.forEach((k, v) -> System.out.println(k + ":" + v));
      // 2. 获取连接池对象
      DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
      conn = dataSource.getConnection();
      System.out.println("conn: " + conn);
      // 3. 获取操作对象
      // 3.1 准备sql语句 - 查询id为2的user
      // String sql = "select * from t_user where id = ?";
      String sql = "select * from t_user";
      pstmt = conn.prepareStatement(sql);
      // 设置sql语句中的第1个参数的值为2
      // pstmt.setInt(1, 2);
      // 4. 执行查询语句
      rs = pstmt.executeQuery();
      List<User> list = new ArrayList<User>();
      while (rs.next()) {
        // 获取返回值
        int id = rs.getInt(1);
        String name = rs.getString(2);
        // String name = rs.getString("name");
        String password = rs.getString("password");
        int age = rs.getInt("age");
        // System.out.println("id=" + id + " name=" + name + " password=" + password + "
        // age=" + age);
        // 将查询结果转换为对象
        User u = new User(id, name, password, age);
        System.out.println(u);
        // 将查询结果存放到一个list中 输出这个list
        list.add(u);
      }
      System.out.println(list);
      System.out.println(list.size());
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }

}